<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // ECMAScript tc39  14种

    // [[scope]]
    // let obj = {name:'张三',age:18}
    // const proxy = new Proxy(obj,{
    //   get(target,key){
    //     return target[key]
    //   },
    //   set(target,key,value){
    //     target[key] = value
    //     return true
    //   },
    //   has(target,value){
    //     console.log('has....');
    //   }
    // })

    // console.log(proxy===obj);
    // console.log(proxy.name);

    // proxy.name = '李四'
    // console.log(proxy.name);


    // console.log('name' in proxy);
    // console.log('name' in obj);

    function myProxy (obj,handler){
      if(!(typeof obj === 'object' && obj!==null)){
        throw new Error('我们的 Cannot create proxy with a non-object as target or handler')
      }

      let _target = deepClone(obj)
      Object.keys(_target).forEach((key)=>{
        // 中间变量
       let temp = {[key]:_target[key]}
        Object.defineProperty(_target,key,{
          get(){
            console.log("key==>", key);
           return handler.get && handler.get(temp, key)
          },
          set(newVal){
            console.log("newVal====>",newVal);
            handler.set && handler.set(temp,key,newVal)
          }
        })
      })
      function deepClone(org,tar){
        var tar = tar || {},
            toStr = Object.prototype.toString,
            attTyep = '[object Array]';
        for(var key in org){
          if(org.hasOwnProperty(key)){
            if(typeof org[key] === 'object' && typeof org[key] !==null){
              tar[key] = toStr.call(org[key]) === arrType?[]:{}
              deepClone(org[key],tar[key])
            } else{
              tar[key] = org[key]
            }
          }
        }
        return tar
      }

       return _target
    }


    var org = {name:'王五',age:18}
    let proxy = new  myProxy(org,{
      get(target,key){
        return target[key]
      },
      set(target,key,value){
        target[key] = value
      }
    })

    console.log(proxy.name);
    proxy.name = '赵六'
    console.log(proxy.name);
    console.log(proxy.age);
    // proxy.name = "赵六"



    // let p1 = new Proxy()

    let p2 = new myProxy()
  </script>
</body>
</html>